<?php

namespace app\admin\controller\uniwigs;

use app\common\controller\Backend;

/**
 * 现金券管理
 *
 * @icon fa fa-circle-o
 */
class Cashcode extends Backend
{
    
    /**
     * CashCode模型对象
     * @var \app\admin\model\CashCode
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('CashCode');
        $this->view->assign("isUseList", $this->model->getIsUseList());
        $this->view->assign("isExchangeList", $this->model->getIsExchangeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }
   
   
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {	
	
			
			
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
		
			
			//每个不同model 的 主键 不一致 默认为id 所以这里搜索要指定为 此model 的主键 id_code 
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(['id_code','group_name','email']);

			
            $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
			
			
		
			
            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
		
			

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
   
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");

	
			
            if ($params)
            {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill)
                {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {	
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
					
					// allowField(true) 过滤post数组中的非数据表字段数据
					$allparams = array();//将批量生成的数据 全部打包
					for($i=0;$i<$params['code_num'];$i++){
						//这里对 折扣券串码 进行唯一字符串生成
						
						
						$allparams[$i] = $params;
						//12位数编码 且 全部大写
						$allparams[$i]['code']=  '';
						//模板卡 全部15位开头 以 TPL 开始
						if( strpos(  $allparams[$i]['group_name'],'tpl-') !== false) {
							
							$allparams[$i]['code'] .='TPL';
						}
						
						$allparams[$i]['code'] .=  strtoupper( substr(  md5(uniqid() . $i)   ,0,12));//uniqid 是基于微妙的 所以也有可能重复 要加上不同标识符
					}
					//调用模型的 批量添加函数 saveAll($allparams) 批量添加数据
					$result = $this->model->allowField(true)->saveAll($allparams);
                    
                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($this->model->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
	
	
	
	/**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get(['id_code'=>$ids]);

        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            if (!in_array($row[$this->dataLimitField], $adminIds))
            {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
					foreach($params as $key=>$a){
						
						$params[$key] = trim($a);
					}
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($row->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
		
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


}
